#include "lineChart.h"
BEGIN_EVENT_TABLE(lineChart,wxPanel)
EVT_PAINT(lineChart::onPaint)
END_EVENT_TABLE()

lineChart::lineChart(wxWindow* parent,wxSize wSize) :
	wxPanel(parent,wxID_ANY,wxDefaultPosition,wSize),
	line1Color(wxColor(255,0,0)),
	line2Color(wxColor(0,255,0))
{

}

void lineChart::DrawLine(wxGCDC& gdc)
{
	if (pointList1.size() == 0 || pointList2.size() == 0)
		return;
	auto drawRealLine = [&](pos pA, pos pB)
	{
		gdc.DrawLine
		(
			wxPoint(winX-(pA.X + xOffset) * xScale,winY-(pA.Y + yOffset) * yScale),
			wxPoint(winX-(pB.X + xOffset) * xScale, winY-(pB.Y + yOffset) * yScale)
		);
	};
	gdc.SetPen(wxPen(line1Color,3));
	auto pL1ptr = pointList1.begin();
	for (; pL1ptr != std::prev(pointList1.end()); pL1ptr++)
		drawRealLine(*pL1ptr, *std::next(pL1ptr));
	gdc.SetPen(wxPen(line2Color,3));
	auto pL2ptr = pointList2.begin();
	for (; pL2ptr != std::prev(pointList2.end()); pL2ptr++)
		drawRealLine(*pL2ptr, *std::next(pL2ptr));
}

void lineChart::DrawBackground(wxGCDC& gdc)
{
	gdc.SetPen(wxPen(wxColor(243, 156, 18), 2));
	double cellX = GetClientSize().x / (pointList1.size() - 1);
	for (int i = 0; i <= pointList1.size(); i++)
		gdc.DrawLine(wxPoint(cellX * i, 0), wxPoint(cellX * i, GetClientSize().y));
	double cellY = GetClientSize().y / 4;
	for (int i = 0; i <= 5; i++)
		gdc.DrawLine(wxPoint(0, cellY * i), wxPoint(GetClientSize().x, cellY * i));
}

void lineChart::onPaint(wxPaintEvent& event)
{
	wxPaintDC pdc(this);
	wxGCDC gdc(pdc);
	DrawBackground(gdc);
	DrawLine(gdc);
}

void lineChart::update()
{
	double min_X = DBL_MAX, max_X = DBL_MIN;
	double min_Y = DBL_MAX, max_Y = DBL_MIN;
	auto findMinMaxItem = [&](std::list<pos>& pl)
	{
		for (const auto& i : pl)
		{
			if (min_Y > i.Y) min_Y = i.Y;
			if (max_Y < i.Y) max_Y = i.Y;
			if (min_X > i.X) min_X = i.X;
			if (max_X < i.X) max_X = i.X;
		}
	};
	findMinMaxItem(pointList1);
	findMinMaxItem(pointList2);
	winX = GetClientSize().x;
	winY = GetClientSize().y;
	
	yOffset = -min_Y;
	xOffset = -min_X;
	xScale = winX / (max_X - min_X);
	yScale = winY / (max_Y - min_Y);

	Refresh();
}
